/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package randominslot;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.ArrayList;
import javax.swing.JOptionPane;

/**
 *
 * @author Libra
 */
public class jFrmGUI extends javax.swing.JFrame {

    /**
     * Creates new form jFrmGUI
     */
    public jFrmGUI() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFileChoose = new javax.swing.JFileChooser();
        jBtnOpenCell = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTxtnConn = new javax.swing.JTextField();
        jBtnRun = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jBtnOpenGroup = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Random Connetion Sim");

        jBtnOpenCell.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jBtnOpenCell.setText("Open");
        jBtnOpenCell.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnOpenCellActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Open Cell No File");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("Number of Connections");

        jTxtnConn.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jBtnRun.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jBtnRun.setText("Run");
        jBtnRun.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnRunActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel3.setText("Run Simulation");

        jBtnOpenGroup.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jBtnOpenGroup.setText("Open");
        jBtnOpenGroup.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnOpenGroupActionPerformed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel4.setText("Open Group Size File");

        jLabel5.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel5.setText("zhangxiaoxing@ion.ac.cn");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(59, 59, 59)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jBtnRun, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jTxtnConn, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jBtnOpenCell)
                                    .addComponent(jLabel1))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jLabel4)
                                    .addComponent(jBtnOpenGroup, javax.swing.GroupLayout.PREFERRED_SIZE, 65, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(jLabel5)
                                .addGap(0, 0, Short.MAX_VALUE))
                            .addComponent(jSeparator1))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(40, 40, 40)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTxtnConn, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jBtnOpenCell)
                    .addComponent(jBtnOpenGroup))
                .addGap(18, 18, 18)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jBtnRun)
                .addGap(18, 18, 18)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addContainerGap(16, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jBtnOpenCellActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnOpenCellActionPerformed
        jFileChoose.setDialogTitle("Open Slot List");
        int openResult = jFileChoose.showOpenDialog(this);
        if (openResult == jFileChoose.APPROVE_OPTION) {
            try {
                FileReader fin =new FileReader(jFileChoose.getSelectedFile().getPath());
                BufferedReader fi=new BufferedReader(fin);
                Cells=new ArrayList(100);
                String line=new String("");
                while ((line=fi.readLine()) != null) {
                    Cells.add(Integer.parseInt(line));
                }
                fi.close();
                fin.close();
//                System.out.println(Cells.size() + " cell count imported");
                noCells=false;
            }
            catch (IOException ioe){
                
            }
        }
    }//GEN-LAST:event_jBtnOpenCellActionPerformed

    private void jBtnRunActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnRunActionPerformed
        if (noCells || noGroups) {
            JOptionPane.showMessageDialog(this, 
                    "Missing File");
//            return;
        }
        else if (Cells.size() != Groups.size()) {
            JOptionPane.showMessageDialog(this, 
                    "Cell and Group number are different");
//            return;
        }
        
        
        else if (jTxtnConn.getText().isEmpty()){
            JOptionPane.showMessageDialog(this, 
                    "Number of Connections Is Empty");
//            return;
        }
        else {
            
            /*
             * TODO standarize
             */
            for (int n=0;n<1000;n++)
            runOnce();

        }

    }//GEN-LAST:event_jBtnRunActionPerformed

    private void jBtnOpenGroupActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnOpenGroupActionPerformed
        
        jFileChoose.setDialogTitle("Open Slot List");
        int openResult = jFileChoose.showOpenDialog(this);
        if (openResult == jFileChoose.APPROVE_OPTION) {
            try {
                FileReader fin =new FileReader(jFileChoose.getSelectedFile().getPath());
                BufferedReader fi=new BufferedReader(fin);
                Groups=new ArrayList(100);
                String line=new String("");
                while ((line=fi.readLine()) != null) {
                    Groups.add(Integer.parseInt(line));
                }
                fi.close();
                fin.close();
//                System.out.println(Groups.size() + " group sizes imported");
                noGroups=false;
            }
            catch (IOException ioe){
                
            }
        }
    }//GEN-LAST:event_jBtnOpenGroupActionPerformed

    private void runOnce() {
            nConn=Integer.parseInt(jTxtnConn.getText());
            nConnNeeded=nConn;
//            System.out.println(nConn+" connections");
            
            /*
            *  Calculate total slots
            */
            for (int i=0;i<Groups.size();i++) {
                totalSlot+=Cells.get(i)*(Groups.get(i)-1);
            }
            nLeft=totalSlot;
//            System.out.println(totalSlot+" slots in total");
        
            /*
            * fill in slots
            */
            for (int i=0;i<Cells.size();i++) {
                int k=Cells.get(i);
                while (k>0 && nConnNeeded>0) {
                    
                    /*
                     * begins new cell
                     */
                    int count=0;
                    for (int m=0;m<Groups.get(i)-1;m++){
                        int rand=r.nextInt(nLeft);
                        if (rand<nConnNeeded) {
                            //connected
                            count++;
//                            System.out.println("Count "+count);
//                            System.out.println("conn "+ (nConn-nConnNeeded+1));
                            nConnNeeded--;
                        }
                        nLeft--;
//                        System.out.println(nLeft + " Left");
                    }
                    dist[count]++;
                    k--;
                }
            } 
        System.out.println(dist[0]+","+dist[1]+","+dist[2]+","+dist[3]);
        
        /*
         * reinit
         */
        totalSlot=0;
        for (int ii=0;ii<4;ii++) dist[ii]=0;
    }
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(jFrmGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(jFrmGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(jFrmGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(jFrmGUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        


        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new jFrmGUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBtnOpenCell;
    private javax.swing.JButton jBtnOpenGroup;
    private javax.swing.JButton jBtnRun;
    private javax.swing.JFileChooser jFileChoose;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField jTxtnConn;
    // End of variables declaration//GEN-END:variables
    
    ArrayList<Integer> Cells;
    ArrayList<Integer> Groups;
    int nConn;
    int totalSlot;
    boolean noGroups=true;
    boolean noCells=true;
//    XORShiftRandom r=new XORShiftRandom();
//    Random r=new Random();
    //TODO Switchable random
    SecureRandom r=new SecureRandom();
    
    int nLeft;
    int nPicked=0;
    int nConnNeeded;
    
    int dist[]=new int[4];

}
